#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>

using namespace std;

int tickets = 10000;

//全局初始化
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// pthread_mutex_t mutex;//锁的声明
#define NAMESIZE 64
typedef struct threadData
{
    char name[NAMESIZE];
    pthread_mutex_t *mutexp;//声明锁
}threadData;

void *startRoutine(void *args)
{
    //const char* name = static_cast<const char *>(args);
    threadData *td = static_cast<threadData*>(args);
    while(true)
    {
        pthread_mutex_lock(td->mutexp);//如果申请不到就会阻塞线程
        if(tickets > 0)
        {
            usleep(1000);
            cout<<td->name<<" 抢到了一张票，票的编号是...."<< tickets << endl;
            tickets--;
            pthread_mutex_unlock(td->mutexp);
            usleep(200);
        }
        else
        {
            cout<<td->name<<" 没有抢到票,没有票了............"<< tickets << endl;
            pthread_mutex_unlock(td->mutexp);
            break;
        }
    }
    return nullptr;
}

int main()
{
    //pthread_mutex_init(&mutex,nullptr);
    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_t tid1,tid2,tid3,tid4;

    threadData *td1 = new threadData();
    strcpy(td1->name,"thread 1");
    td1->mutexp = &mutex;
    pthread_create(&tid1,nullptr,startRoutine,td1);

    threadData *td2 = new threadData();
    strcpy(td2->name,"thread 2");
    td2->mutexp = &mutex;
    pthread_create(&tid2,nullptr,startRoutine,td2);

    threadData *td3 = new threadData();
    strcpy(td3->name,"thread 3");
    td3->mutexp = &mutex;
    pthread_create(&tid3,nullptr,startRoutine,td3);

    threadData *td4 = new threadData();
    strcpy(td4->name,"thread 4");
    td4->mutexp = &mutex;
    pthread_create(&tid4,nullptr,startRoutine,td4);



    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    pthread_join(tid4,nullptr);

    //pthread_mutex_destroy(&mutex);



    return 0;
}